package com.study.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.druid.pool.xa.DruidXADataSource;

@Configuration
@MapperScan(basePackages = { "com.study.mapper.db1" }, sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DB1Config {

	private final static String DB1_PLAINTEXT = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALKV4BMcupM+MdE63YNXEJxLU1q6Xft6EZEWzZg1uC5D8fIZGNiYIyv0eStJ/NpsE7L7vOtCjsynvFzQUph6rYECAwEAAQ==";

	@Bean(name = "db1DataSource")
	public DataSource dataSourceCar(@Qualifier("db1Porperty") DruidXADataSource druidXADataSource) {
		AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
		try {
			String plainText = ConfigTools.decrypt(DB1_PLAINTEXT, druidXADataSource.getPassword());
			druidXADataSource.setPassword(plainText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		xaDataSource.setXaDataSource(druidXADataSource);
		xaDataSource.setUniqueResourceName("db1DataSource");
		return xaDataSource;
	}

	@Bean(name = "db1SqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// 扫描指定目录的xml
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:mapping/db1/*Mapper.xml"));
		return bean.getObject();
	}

	@Bean(name = "db1SqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(
			@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
